package com.lujianfei.componentdesign

import androidx.fragment.app.Fragment
import com.lujianfei.common.BaseActivity
import com.lujianfei.common.BaseFragment
import com.lujianfei.componentdesign.widget.CustomTab
import com.lujianfei.componentdesign.widget.CustomTabHost
import com.lujianfei.router_api.Router

class MainActivity : BaseActivity() {

    private var customTabHost:CustomTabHost ?= null
    private var mCurrentFragment: Fragment?= null

    override fun resouceId() = R.layout.activity_main

    override fun initView() {
        customTabHost = findViewById(R.id.customTabHost)
        customTabHost?.addTab(CustomTab(this).setTabTitle("首页").setTabSelected(true))
        customTabHost?.addTab(CustomTab(this).setTabTitle("我的"))

        Router.instance.getFragment(Router.FragmentKey.HOME)?.let {
            switchFragment(it)
        }
    }

    override fun initData() {
    }

    override fun initEvent() {
        customTabHost?.onTabClickListener = { tab->
            if (tab.title == "首页") {
                Router.instance.getFragment(Router.FragmentKey.HOME)?.let {
                    switchFragment(it)
                }
            } else if (tab.title == "我的") {
                Router.instance.getFragment(Router.FragmentKey.ME)?.let {
                    switchFragment(it)
                }
            }
        }
    }

    private fun switchFragment(targetFragment: Fragment) {
        val beginTransaction = supportFragmentManager.beginTransaction()
        if (mCurrentFragment != targetFragment) {
            mCurrentFragment?.let {
                beginTransaction.hide(it)
            }
            if (targetFragment.isAdded) {
                beginTransaction.show(targetFragment)
            } else {
                beginTransaction.add(R.id.fragmentContainer, targetFragment)
            }
            mCurrentFragment = targetFragment
        }
        beginTransaction.commitAllowingStateLoss()
    }
}